package net.zm123.async;

import com.nfk.grpc.MyServiceGrpc;
import com.nfk.grpc.MyServiceOuterClass;
import io.grpc.stub.StreamObserver;

import java.util.concurrent.CompletableFuture;

public class RpcAsyncServerImpl extends MyServiceGrpc.MyServiceImplBase {
    @Override
    public void actionMethod(MyServiceOuterClass.ActionRequest request, StreamObserver<MyServiceOuterClass.ActionResponse> responseObserver) {
        CompletableFuture.supplyAsync(() -> {
            final String result = this.setParamsWithTcp2Terminal();
            return result;
        }).thenAccept(result -> {
            //正常
            //创建rpc返回
            MyServiceOuterClass.ActionResponse response =
                    MyServiceOuterClass.ActionResponse.newBuilder()
                            //todo
                            .setMessage("success")
                            .build();
            responseObserver.onNext(response);
            responseObserver.onCompleted();

        }).exceptionally(err -> {
            //异常
            //创建rpc返回
            MyServiceOuterClass.ActionResponse response =
                    MyServiceOuterClass.ActionResponse.newBuilder()
                            //todo
                            .setMessage(err.getMessage())
                            .build();
            responseObserver.onNext(response);
            responseObserver.onCompleted();
            return null;
        });
    }

    /**
     * 模拟异步通信，比如和客户端进行通信 并等待结果
     *
     * @return
     */
    private String setParamsWithTcp2Terminal() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return "设置成功";
    }
}
